﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Diagnostics;
using System.IO;

namespace ConcordWinManager
{
    public partial class MainForm : Form
    {
        Contract contract;

        public MainForm()
        {
            InitializeComponent();
            //Form1 f = new Form1();
            //f.ShowDialog();

            //Tools.RunWithProgressIndicator(this, delegate { for (; ; );});

        }

        /// <summary>
        /// Выход из приложения
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void выходToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// Открытие формы консультантов
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void консультантыToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ConsultantForm consultantForm = new ConsultantForm();
            consultantForm.ShowDialog();
        }

        /// <summary>
        /// Открытие формы контрагентов с выбранным типом "ФЛ"
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void физлицаToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ContragentForm contragentForm = new ContragentForm(this, "ФЛ");
            contragentForm.ShowDialog();
        }

        /// <summary>
        /// Открытие формы контрагентов с выбранным типом "ЮЛ"
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void юрлицаToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ContragentForm contragentForm = new ContragentForm(this, "ЮЛ");
            contragentForm.ShowDialog();
        }

        /// <summary>
        /// Открытие формы контрагентов с выбранным типом "ИП"
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void иПToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ContragentForm contragentForm = new ContragentForm(this, "ИП");
            contragentForm.ShowDialog();
        }

        /// <summary>
        /// Открытие формы заключения нового договора
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void новыйДоговорToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Settings.consultant.user.CanAddContract)
            {
                ContractEditForm contractForm = new ContractEditForm(this, "Добавление");
                contractForm.ShowDialog();

                UpdateForm();

                Tools.SelectRowInDataGridViewById("id_contract", contractForm.contract.id_contract, ref bs);
            }
            else
            {
                MessageBox.Show("Недостаточно прав для заключения договора. Обратитесь к администратору", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// Для неоплаченных договоров
        /// </summary>
        BindingSource bs = new BindingSource();

        /// <summary>
        /// Для оплаченных договоров
        /// </summary>
        BindingSource bs2 = new BindingSource();

        /// <summary>
        /// Обновление формы
        /// </summary>
        public void UpdateForm()
        {
            DataSet ds = new DataSet();
            Tools.RunWithProgressIndicator(this, delegate { contract.SelectAll(ref ds); });

            if (ds.Tables.Count > 0)
            {
                bs.DataSource = null;
                bs.Filter = "";
                bs.DataSource = ds.Tables[0];

                dataGridViewTable.DataSource = bs; //ds.Tables[0];

                dataGridViewTable.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

                dataGridViewTable.Columns[0].Visible = false;
                dataGridViewTable.Columns[1].Visible = false;

                dataGridViewTable.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
                dataGridViewTable.Columns[4].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
                dataGridViewTable.Refresh();
            }
            if (ds.Tables.Count > 1)
            {
                bs2.DataSource = null;
                bs2.Filter = "";
                bs2.DataSource = ds.Tables[1];

                dataGridViewTable2.DataSource = bs2; //ds.Tables[0];

                dataGridViewTable2.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

                dataGridViewTable2.Columns[0].Visible = false;
                dataGridViewTable2.Columns[1].Visible = false;

                dataGridViewTable2.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
                dataGridViewTable2.Columns[4].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;

                dataGridViewTable2.Refresh();
            }
            //dataGridViewTable.Rows[1].DefaultCellStyle.BackColor = Color.YellowGreen;       

        }

        /// <summary>
        /// Событие на загрузку формы
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Load(object sender, EventArgs e)
        {
            AboutProgramForm apf = new AboutProgramForm();

            this.Text = string.Format("{0} v{1}", apf.AssemblyTitle, apf.AssemblyVersion);

            Settings.Load();

            LoginForm loginForm = new LoginForm();
            loginForm.ShowDialog();

            if (!loginForm.Success)
            {
                this.Close();
                return;
            }

            администированиеToolStripMenuItem.Visible = Settings.consultant.user.IsAdminRole;
            toolStripStatusLabelAdminRole.Visible = Settings.consultant.user.IsAdminRole;

            string temporaryFolder = Path.GetTempPath() + @"ConcordWinManager\templates\tmp";
            if (!Directory.Exists(temporaryFolder))
            {
                Directory.CreateDirectory(temporaryFolder);
            }

            toolStripStatusLabelUserInfo.Text += string.Format(" {0} {1} {2}",
                Settings.consultant.Family,
                Settings.consultant.Name,
                Settings.consultant.FName);


            this.contract = new Contract();

            UpdateForm();

        }

        /// <summary>
        /// Событие на закрытие формы
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Settings.Save("ConcordWinManager.exe");
        }

        /// <summary>
        /// Открытие информации о программе
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void оПрограммеToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutProgramForm aboutProgramForm = new AboutProgramForm();
            aboutProgramForm.ShowDialog();
        }

        /// <summary>
        /// Открытие справки
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void помощьToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                Process.Start(@"Docs\Manual.mht");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка: Не удалось открыть справку. Original error: " + ex);
            }
        }

        /// <summary>
        /// Внесение оплаты
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void внестиОплатуToolStripMenuItem_Click(object sender, EventArgs e)
        {

            Oplata oplata = new Oplata();
            decimal d = 0;

            Tools.RunWithProgressIndicator(this, delegate
            {

                string contractNumber = dataGridViewTable.Rows[dataGridViewTable.SelectedCells[0].RowIndex].Cells["Номер договора"].Value.ToString();
                string[] tmp = contractNumber.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);

                oplata.Definition = string.Format("оплата по договору {0} от {1}",
                    contractNumber,
                    tmp[0]);

                oplata.id_contract = int.Parse(dataGridViewTable.Rows[dataGridViewTable.SelectedCells[0].RowIndex].Cells["id_contract"].Value.ToString());

                d = decimal.Parse(dataGridViewTable.Rows[dataGridViewTable.SelectedCells[0].RowIndex].Cells["Остаток"].Value.ToString());

                oplata.contract.SelectById(oplata.id_contract);
            });

            OplataForm oplataForm = new OplataForm(oplata, d);

            oplataForm.ShowDialog();

            UpdateForm();

        }

        /// <summary>
        /// Быстрый поиск по договорам при вводе текста в поле поиска
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbxQuickSearch_TextChanged(object sender, EventArgs e)
        {
            Tools.QuickSearch(tbxQuickSearch.Text.Trim(), dataGridViewTable.Columns, ref this.bs);
            Tools.QuickSearch(tbxQuickSearch.Text.Trim(), dataGridViewTable.Columns, ref this.bs2);

        }

        /// <summary>
        /// Добавление рекламации
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void новаяРекламацияToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ReclamationEditForm reclamationEditForm = new ReclamationEditForm(this, "Добавление");
            reclamationEditForm.ShowDialog();
        }

        /// <summary>
        /// Добавление монтажа
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void новыйToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            InstallationEditForm installationEditForm = new InstallationEditForm(this, "Добавление");
            installationEditForm.ShowDialog();
        }

        /// <summary>
        /// Добаление замера
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void выписатьБланкToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ZamerEditForm zamerEditForm = new ZamerEditForm(this, "Добавление");
            zamerEditForm.ShowDialog();
        }

        private void договораToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AllReportForm allReportForm = new AllReportForm();
            allReportForm.ShowDialog();
        }

        private void шаблоныToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TemplateForm templateForm = new TemplateForm(this);
            templateForm.ShowDialog();
        }


        /// <summary>
        /// Открытие формы резидентов
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void резидентыToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RezidentForm rezidentForm = new RezidentForm(this);
            rezidentForm.ShowDialog();
        }

        private void произведенныеToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AllReportForm allReportForm = new AllReportForm();
            allReportForm.ShowDialog();
        }

        private void генерацияОтчетовToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AllReportForm allReportForm = new AllReportForm();
            allReportForm.ShowDialog();
        }

        /// <summary>
        /// Верхний датагрид
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void удалитьToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Settings.consultant.user.CanDeleteContract)
            {
                DeleteForm deleteForm = new DeleteForm();
                deleteForm.ShowDialog();

                bool b = false;

                if (deleteForm.DialogResult == DialogResult.OK)
                {

                    b = this.contract.DeleteById((int)dataGridViewTable.Rows[dataGridViewTable.SelectedCells[0].RowIndex].Cells["id_contract"].Value,
                        Settings.consultant.id_consultant, deleteForm.ReasonDelete, deleteForm.ShowInReport);

                    if (b)
                    {
                        MessageBox.Show("Договор удален успешно", "Информация!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("Договор НЕ удален", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }

                    UpdateForm();
                }
            }
            else
            {
                MessageBox.Show("Недостаточно прав для удаления договора. Обратитесь к администратору", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// Нижний датагрид
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void удалитьToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            if (Settings.consultant.user.CanDeleteContract)
            {
                DeleteForm deleteForm = new DeleteForm();
                deleteForm.ShowDialog();

                bool b = false;

                if (deleteForm.DialogResult == DialogResult.OK)
                {

                    b = this.contract.DeleteById((int)dataGridViewTable2.Rows[dataGridViewTable2.SelectedCells[0].RowIndex].Cells["id_contract"].Value,
                        Settings.consultant.id_consultant, deleteForm.ReasonDelete, deleteForm.ShowInReport);

                    if (b)
                    {
                        MessageBox.Show("Договор удален успешно", "Информация!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("Договор НЕ удален", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }

                    UpdateForm();
                }
            }
            else
            {
                MessageBox.Show("Недостаточно прав для удаления договора. Обратитесь к администратору", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// Отображение меню действий с договорами
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridViewTable_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e)
        {
            try
            {
                dataGridViewTable.Rows[e.RowIndex].Selected = true;
                e.ContextMenuStrip = contextMenuStrip;

                decimal d = decimal.Parse(dataGridViewTable.Rows[dataGridViewTable.SelectedCells[0].RowIndex].Cells["Остаток"].Value.ToString());
                if (d > 0)
                {
                    внестиОплатуToolStripMenuItem.Enabled = true;
                }
                else
                {
                    внестиОплатуToolStripMenuItem.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Произошла ошибка при вызове функции оплаты \n\nПодробнее:\n" + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dataGridViewTable2_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e)
        {
            try
            {
                dataGridViewTable2.Rows[e.RowIndex].Selected = true;
                e.ContextMenuStrip = contextMenuStrip2;

                decimal d = decimal.Parse(dataGridViewTable2.Rows[dataGridViewTable2.SelectedCells[0].RowIndex].Cells["Остаток"].Value.ToString());
                if (d > 0)
                {
                    внестиОплатуToolStripMenuItem2.Enabled = true;
                }
                else
                {
                    внестиОплатуToolStripMenuItem2.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Произошла ошибка при вызове функции оплаты \n\nПодробнее:\n" + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// Нижний датагрид, не используется, т.к. договора оплачены
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void внестиОплатуToolStripMenuItem2_Click(object sender, EventArgs e)
        {

        }


        /// <summary>
        /// Просмотр информации о договоре (просмотр оплат)
        /// </summary>
        /// <param name="id_contract"></param>
        private void ViewContractInfo(int id_contract)
        {
            OplataInfForm oplataInfFrm = new OplataInfForm(this, id_contract);
            oplataInfFrm.ShowDialog();

            UpdateForm();
            
            Tools.SelectRowInDataGridViewById("id_contract", id_contract, ref bs);
            Tools.SelectRowInDataGridViewById("id_contract", id_contract, ref bs2);
        }

        /// <summary>
        /// Просмотр оплат в неоплаченных договорах
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void просмотрОплатToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ViewContractInfo((int)dataGridViewTable.Rows[dataGridViewTable.SelectedCells[0].RowIndex].Cells["id_contract"].Value);
        }

        /// <summary>
        /// Просмотр оплат в оплаченных договорах
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void просмотрОплатToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ViewContractInfo((int)dataGridViewTable2.Rows[dataGridViewTable2.SelectedCells[0].RowIndex].Cells["id_contract"].Value);
        }


        /// <summary>
        /// Просмотр договора в неоплаченных договорах
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void открытьВWordToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ContractEditForm contractEditFrm = new ContractEditForm();
            contractEditFrm.ViewContract((int)dataGridViewTable.Rows[dataGridViewTable.SelectedCells[0].RowIndex].Cells["id_contract"].Value);
        }

        /// <summary>
        /// Просмотр договора в оплаченных договорах
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void открытьВWordToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ContractEditForm contractEditFrm = new ContractEditForm();          
            contractEditFrm.ViewContract((int)dataGridViewTable2.Rows[dataGridViewTable2.SelectedCells[0].RowIndex].Cells["id_contract"].Value);
        }



    }
}